import 'dart:convert';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/entity/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/views/Dynamic/DynamicItem.dart';
import 'package:thinking/widget/_.dart';
import 'package:thinking/service/_.dart';

class Personal extends StatefulWidget {

  final int userId;
  Personal({required this.userId});

  @override
  _Personal createState() => _Personal(userId: userId);
}



class _Personal extends State<Personal>  {


  late int personalType ;
  Map<String, dynamic> userInfoJson =
      jsonDecode(SPreferences().getString('user_UserInfo'));
  List<Map<String, String>> titleList = [
    {'title': '动态', 'dataName': 'user_DynamicNum'},
    {'title': '关注', 'dataName': 'user_Follows'},
    {'title': '粉丝', 'dataName': 'user_Fans'}
  ];
  List<Map<String, dynamic>> myDataList = [
    {'title': '被我赞过', 'titleIcon': Icons.thumb_up_alt_outlined},
    {'title': '我的收藏', 'titleIcon': Icons.star_border_outlined},
    {'title': '历史记录', 'titleIcon': Icons.timer},
    {'title': '我的订阅', 'titleIcon': Icons.done}
  ];
  List<Map<String, dynamic>> moreDataList = [
    {'title': '更改资料', 'titleIcon': Icons.art_track},
    {'title': '清除缓存', 'titleIcon': Icons.delete_outline},
    {'title': '查看更新', 'titleIcon': Icons.cloud_done_outlined},
    {'title': '联系客服', 'titleIcon': Icons.supervised_user_circle_sharp},
    {'title': '赞助我们', 'titleIcon': Icons.monetization_on_outlined}
  ];
  late Future<dynamic> _function;
  late UserData userData;
  String cacheSize = "0.00B";
  late List<DynamicDataEntity> dynamicList = [];
  int userId;
  late OnlyDynamicPageEntity onlyDynamicPageEntity;
  late EasyRefreshController _easyRefreshController;
  _Personal({required this.userId});

  Widget title() {
    return UserItemWidget(
        panelLeft: 5,
        userData: userData,
        showButton: personalType == 0,
        showDivider: false,
        titleColor: personalType == 1?ColorConfig.ThemeColor:ColorConfig.BlackBackColor,
    );
  }

  PreferredSize bottom() {
    return PreferredSize(
        preferredSize: Size.fromHeight(Screen.setHeight(65)),
        child: Container(
          width: Screen.width(context),
          height: Screen.setHeight(65),
          child: Row(
            children: titleList.asMap().keys
                .map((e) =>

                  Flexible(child: GestureDetector(
                    onTap: (){
                      if(e!=0 || personalType!=0){
                          Modular.to.pushNamed('/personalTopItem/$userId/$e/${userData.userNickName != '暂无'?userData.userNickName:userData.userPhone}');
                      }
                    },
                    child: Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            titleList[e]['title'] == '动态'?userData.userUserInfo!.userDynamicNum.toString():(userData.toJson())[titleList[e]['dataName']].toString(),style: TextStyle(
                              fontWeight: FontWeight.bold
                          ),),
                          Text(titleList[e]['title'].toString(),style: TextStyle(
                              fontSize: 13,
                              color: ColorConfig.TextColor
                          ),)
                        ],
                      ),
                    ),
                  ),flex: 1,),
            )
                .toList(),
          ),
        ));
  }

  Widget myDataWidget(){
    return Panel(
        bottom: 20,
        left: 0,
        right: 0,
        child: Container(
          width: Screen.width(context),
          height: Screen.setHeight(65),
          child: Row(
            children: myDataList.asMap().keys.map((e) => Flexible(
              flex: 1,
              child: GestureDetector(
                child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(myDataList[e]['titleIcon'],color: ColorConfig.ThemeObsColor,size: 27,),
                Text(myDataList[e]['title'],style: TextStyle(fontSize: 13),)
              ],
            ),
            ),
            onTap: (){
                  if(e == 3){
                    Modular.to.pushNamed('/personalSub');
                  }else{
                    Modular.to.pushNamed('/personalTitleBottom/$e');
                  }
            },
            ),
            )).toList(),
          ),
        ));
  }

  Widget moreDataWidget(){

    return Panel(child: Column(
      children: moreDataList.map((e) => Column(
        children: [
          GestureDetector(
            onTap: () async {
              switch(e['title']){
                case '清除缓存':
                  return await clearCache();
                case '联系客服':
                  Modular.to.pushNamed('/personalCustomer');
                  return;
                case '赞助我们':
                  Modular.to.pushNamed('/personalPay');
                  return;
                case '查看更新':
                  bool status = await CheckUpdate().check(context);
                  if (!status) {
                    BotToast.showText(text: '已是最新版');
                  }
                  return;
                case '更改资料':
                  Modular.to.pushNamed('/personalUpdateData');
                  return;
                default:
                  return;
              }
            },
            child: ListTile(
              leading: Icon(e['titleIcon'],color: ColorConfig.ThemeObsColor,),
              title: Text(e['title']),
              trailing: e['title'] == '清除缓存'?Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(cacheSize.toString(),style: TextStyle(fontWeight: FontWeight.bold),),
                  SizedBox(width: 5,),
                  Icon(Icons.arrow_forward_ios,color: ColorConfig.TextColor,)
                ],
              ):Icon(Icons.arrow_forward_ios,color: ColorConfig.TextColor,),
            ),
          ),
          Divider()
        ],
      )).toList(),
    ),left: 15,right: 0,);

  }

  Future<void> computeCache() async {
    String size = await ClearCache.loadCache();
    setState(() {
      cacheSize = size;
    });
  }


  @override
  void initState() {
    super.initState();
    personalType = userId == SPreferences().getInt('user_Id')?1:0;
    _function = future();
    computeCache();
  }

  future() async {
    if(personalType == 0){
      await HomeService.setRecentVisit(params: {
        'recentVisit_Type':2,
        'user_Id':SPreferences().getInt('user_Id'),
        'thing_Id':userId
      });
    }
    await getUserData();
  }

  Future<void> getUserData() async {
    userData = await UserService.getUserData(
        params: {'user_Id': userId,'my_Id':SPreferences().getInt('user_Id')});
    if(personalType == 0){
      onlyDynamicPageEntity = OnlyDynamicPageEntity();
      _easyRefreshController = EasyRefreshController();
      await getDynamicData();
    }
  }

  Future<void> getDynamicData() async{
    List<DynamicDataEntity> res =
    (  await UserService.getUserDynamic(params: {
      'dynamic_Page':onlyDynamicPageEntity.dynamicPage,
      'dynamic_Count':onlyDynamicPageEntity.dynamicCount,
      'user_Id':userId,
      'my_Id':SPreferences().getInt('user_Id')
    })).dynamicList!;
    if (!onlyDynamicPageEntity.canDynamic) {
      BotToast.showText(text: '没有更多动态了哦~');
    }
    if (res.length < onlyDynamicPageEntity.dynamicCount && onlyDynamicPageEntity.canDynamic) {
      onlyDynamicPageEntity.setDynamicPage = onlyDynamicPageEntity.dynamicPage +1;
      onlyDynamicPageEntity.setCanDynamic = false;
    }
    dynamicList = [...dynamicList,...res];
    setState(() {

    });
  }

  Widget easyRefresh(Widget child) {
    return EasyRefresh(
      child: child,
      header: BezierCircleHeader(backgroundColor: ColorConfig.ThemeColor),
      footer: BezierBounceFooter(backgroundColor: ColorConfig.ThemeColor),
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _easyRefreshController,
      bottomBouncing: true,
      onLoad: () async {
        if (onlyDynamicPageEntity.canDynamic){
          onlyDynamicPageEntity.setDynamicPage = onlyDynamicPageEntity.dynamicPage + 1;
        }
        await getDynamicData();
        _easyRefreshController.finishLoad(success: true);
      },
    );
  }

  Future<void> clearCache() async{
    var simpleCallBack = await showDialog(
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: Text('是否清除缓存'),
          children: <Widget>[
            Container(
              height: 80,
              alignment: Alignment.center,
              child: Text('清除后,会关闭程序!! 请自行重启'),
            ),
            Divider(
              height: 1,
            ),
            TextButton(
              child: Text('确认',style: TextStyle(color: ColorConfig.ThemeColor,fontSize: 16,fontWeight: FontWeight.bold),),
              onPressed: () {
                Navigator.of(context).pop('ok');
              },
            ),
            Divider(
              height: 1,
            ),
            TextButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop('cancel');
              },
            ),
          ],
        );
      },
    );
    if (simpleCallBack == 'ok') {
      bool status = await ClearCache.clearCache();
      await computeCache();
      if (status) {
        exit(0);
      }else{
        BotToast.showText(text: '清除失败!');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder(
        future: _function,
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          return snapshot.connectionState == ConnectionState.done?NestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[SliverAppBar(
                pinned: true,
                title: title(),
                bottom: bottom(),
                elevation: 0,
                backgroundColor: ColorConfig.WhiteBackColor,
                automaticallyImplyLeading: false,
                titleSpacing: 0,
              ),
              ];
            },
            body: personalType == 0? MediaQuery.removePadding(removeTop: true, context: context,
            child:  easyRefresh(
                Empty(child: ListView(
                  shrinkWrap: true,
                  physics: BouncingScrollPhysics(),
                  children: dynamicList
                      .asMap().keys.map((e) => Column(
                    children: [
                      e == 0?Container():Line(),
                      DynamicItem(
                        dynamicData: dynamicList[e],
                        key: ValueKey(dynamicList[e].dynamicId),
                      )
                    ],
                  )).toList(),
                ),isShow: dynamicList.length == 0,)))

            :
              MediaQuery.removePadding(removeTop: true, context: context,
              child: ListView(
                shrinkWrap: true,
                physics: BouncingScrollPhysics(),
                children: [
                  myDataWidget(),
                  Container(
                    margin: EdgeInsets.only(left: 10),
                    child: Text(
                      '更多服务',
                      style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.bold
                      ),
                    ),
                  ),
                  moreDataWidget(),
                ],
              )) ,
            ) :Loading();
        },),
    );
  }
}
